package EmpDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import util.DBUtil;

public class EmpDao {
	public List<Emp> findAll(){
		String sql="select id,name,salary,age from t_emp_winner order by id";
		
	
		
		Connection conn=null;
		PreparedStatement pstmt=null;

	    try {
			conn=DBUtil.getConnection();
			pstmt=conn.prepareStatement(sql);
			ResultSet rs=pstmt.executeQuery();
			List<Emp> list=new ArrayList();
			while(rs.next()){
				Emp emp=new Emp();
				emp.setId(rs.getInt("id"));
				emp.setName(rs.getString("name"));
				emp.setSalary(rs.getDouble("salary"));
				emp.setAge(rs.getInt("age"));
				list.add(emp);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("查询全部的员工失败",e);
		}finally{
			DBUtil.close(conn);
		}  
	}
	
	public void save(Emp emp){
		String sql="insert into t_emp_winner values(emp_winner_seq.nextval,?,?,?)";
		Connection con=null;
		try {
			con=DBUtil.getConnection();
			PreparedStatement ps=con.prepareStatement(sql);
			ps.setString(1, emp.getName());
			ps.setDouble(2, emp.getSalary());
			ps.setInt(3, emp.getAge());
			ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("插入员工失败",e);
		}finally{
			DBUtil.close(con);
		}	
	}
	public void delete(int id){
		String sql="delete from t_emp_winner where id=?";
		Connection con=null;
		
		try {
			con=DBUtil.getConnection();
			PreparedStatement ps=con.prepareStatement(sql);
			ps.setInt(1, id);
			ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("删除员工失败",e);
		}finally{
			DBUtil.close(con);
		}
	}
	
	public static void main(String[] args) {
		EmpDao dao=new EmpDao();
		Emp emp=new Emp();
		emp.setName("唐僧");
		emp.setSalary(9000.0);
		emp.setAge(30);
		/*dao.save(emp);
		
		dao.delete(295);*/
		List<Emp>list=dao.findAll();
		for(Emp e:list){
			System.out.println(e);
		}
	
		
	}
	
}


